<template>
  <div>
    <!-- 顶部导航 -->
    <van-nav-bar title="编辑昵称" left-text="取消" right-text="保存" @click-left="onClickLeft" @click-right="onClickRight" />

    <!-- 输入框 -->
    <van-field v-model="value" type="textarea" maxlength="8" placeholder="请输入昵称" show-word-limit />
  </div>
</template>

<script>
import { setUserprofile } from '@/api/user.js'
export default {
  data () {
    return {
      // 输入框内容
      value: this.username
    }
  },
  props: {
    // 原昵称
    username: {
      type: String,
      require: true
    }
  },
  model: {
    prop: 'username'
  },
  methods: {
    // 关闭弹层
    onClickLeft () {
      this.$emit('leftClose')
    },
    // 保存
    async onClickRight () {
      if (this.value.trim() === '') return this.$toast('不能为空')
      this.$toast.loading({
        message: '修改中...',
        forbidClick: true,
        duration: 0
      })
      try {
        await setUserprofile({
          name: this.value
        })
        this.$toast('修改昵称成功')
        // 关闭弹出层
        this.$emit('leftClose')
        // 同步视图
        this.$emit('input', this.value)
      } catch (err) {
        console.dir(err)
        if (err.response.status === 409) return this.$toast('用户名已存在')
        this.$toast('修改昵称失败')
      }
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
</style>
